<?php
require_once '../../server/utils/functions.php';
require_once '../../server/model/Incident.php';
require_once '../../server/model/Machine.php';
$db = db();
$query = Array();
$parameters = Array();
if(isset($_GET["machine"])&& !empty($_GET["machine"])){
    $parameters["machine"] = utf8_decode(htmlentities($_GET["machine"]));
    $query[] = " MAC_ID=:machine";
}
if(isset($_GET["id"])&& !empty($_GET["id"])){
    $parameters["id"] = utf8_decode(htmlentities($_GET["id"]));
    $query[] = " INC_ID=:id";
}
$where = "";
if(sizeof($query)>0){
    $where.=" WHERE";
    $i = 0;
    foreach($query as $condition){
        if($i!=0){
            $where .= " AND";
        }
        $where .= $condition;
        $i++;
    }
}
$req = $db->prepare("SELECT MAC_ID, MAC_IP_ADDR, MAC_INFOS, MAC_RAM, MAC_DISK, INC_ID, INC_DATE, TIN_LABEL, INC_INFOS, INC_DATE_RES FROM INCIDENT JOIN MACHINE USING(MAC_ID) JOIN TYPE_INCIDENT ON TYPE_INCIDENT.TIN_ID = INCIDENT.INC_TYPE".$where);
$req->execute($parameters);
$response = Array();

while($datas = $req->fetch()){
    $machine = new Machine(utf8_encode($datas["MAC_IP_ADDR"]), utf8_encode($datas["MAC_INFOS"]), $datas["MAC_RAM"], $datas["MAC_DISK"]);
    $machine->setId($datas["MAC_ID"]);
    $incident = new Incident($machine,$datas["INC_DATE"], utf8_encode($datas["TIN_LABEL"]), utf8_encode($datas["INC_INFOS"]), $datas["INC_DATE_RES"]);
    $incident->setId($datas["INC_ID"]);
    $response[]=$incident;
}
if(isset($_GET["type"]) && $_GET["type"]=="xml"){
//    $xml = new SimpleXMLElement('<salles/>');
    $domtree = new DOMDocument('1.0', 'UTF-8');
    $xmlRoot = $domtree->createElement("incidents");
    foreach ($response as $incident) {
        $xmlRoot->appendChild($incident->xmlSerialize($domtree));
    }
    $domtree->appendChild($xmlRoot);

    Header('Content-type: text/xml');
    echo $domtree->saveXML();
}else{
    Header('Content-type: text/json');
    echo json_encode($response);
}
$req->closeCursor();
?>
